/*********************TCP接收函数*********************/
#include "connect.h"
void *tcpserver(void* arg)
{
    int tlistenfd;   //监听套接字
    int tconnfd;    //连接后的套接字
    int res;
    struct sockaddr_in servaddr,cliaddr;
    socklen_t peerlen;
    char ttransbuf[128];//tcp传输用的buf

    pthread_mutex_lock(&work_mutex); //加锁
    printf("lock\n");
    //初始化互斥锁
    if (0 != (res = pthread_mutex_init(&work_mutex, NULL)))
    {
        perror("pthread_mutex_init");
        exit(-1);
    }

    //建立socket连接
    if (-1 == (tlistenfd = socket(AF_INET,SOCK_STREAM,0)))
    {
        perror("socket");
        exit(-1);
    }
    printf("tlistenfd is %d\n",tlistenfd);
    //设置sockaddr_in结构体中相关的参数
    bzero(&servaddr,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi("9999"));
    servaddr.sin_addr.s_addr = inet_addr("0.0.0.0");
    //绑定函数
    if (bind(tlistenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)
    {
        perror("bind");
        exit(-1);
    }

    printf("bind success\n");
    //调用listen函数，设置监听模式
    if (-1 == listen(tlistenfd,10))
    {
        perror("listen");
        exit(-1);
    }
    printf("listening\n");
    //调用accept函数，等待客户端的连接
    peerlen = sizeof(cliaddr);
    while(1)
    {
        printf("waiting for accepting\n");
        r_msg_num = 0;//输入消息的总条目数
        if ((tconnfd = accept(tlistenfd,(struct sockaddr *)&cliaddr,&peerlen)) < 0)
        {
            perror("accept");
            exit(-1);
        }
        //调用recv函数接收发送端发来的数据
        memset(ttransbuf,0,sizeof(ttransbuf));
        if (-1 == recv(tconnfd,ttransbuf,128,0))
        {
            perror("recv");
            exit(-1);
        }
        //strcpy(recvemsg,ttransbuf);   //收到的消息拷贝到recvmsg中
        printf("message %s received\n",ttransbuf);
        //puts(ttransbuf);
        //r_msg_num++;             //消息总条目数++

        //strcpy(allrecvmsg[r_msg_num],recvemsg);//每一条消息存到一个二维数组中
        close(tconnfd);
    }

    pthread_mutex_unlock(&work_mutex); //解锁
    printf("unlock\n");
    close(tlistenfd);
    //exit(0);
    pthread_exit(NULL);
}
